/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msstudio.message;

import com.msstudio.midlets.MSCMIDlet;
import com.msstudio.websocket.client.WebSocketClient;
import com.msstudio.websocket.client.api.WebSocketClientListener;
import com.msstudio.websocket.client.api.WebSocketPacket;
import com.msstudio.websocket.client.event.WebSocketClientEvent;
import java.io.IOException;

/**
 *
 * @author sunnyz
 */
public class MessageHandler implements WebSocketClientListener {

    public MessageHandler() {
    }

    public void initialize(WebSocketClient webSocketClient) {
        webSocketClient.addListener(this);
    }

    public void processOpened(WebSocketClientEvent aEvent) {
    }

    public void processPacket(WebSocketClientEvent aEvent, WebSocketPacket aPacket) {
        if (aPacket.getFrameType() == WebSocketPacket.FRAMETYPE_UTF8) {
            return; // text frame is not expected
        }
        byte[] msgBytes = aPacket.getByteArray();
        Msg msg = null;
        try {
            msg = Msg.parseFrom(msgBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (msg == null) {
            System.out.println("Unknown message:  null");
            return;
        }
        String msgHead = msg.getMsgHead();
        if (msgHead == null || msgHead.length() == 0) {
            System.out.println("Unknown message: " + msgHead.toString());
            return;
        }
        if ("Login".equals(msgHead)) {
            handleLogin(msg.getMsgBody().toByteArray());
            return;
        }
    }

    public void processClosed(WebSocketClientEvent aEvent) {
    }

    public void handleLogin(byte[] messageBytes) {
        if (MSCMIDlet.mainForm.iFirstTimeQuery) {
            //httpPoster.getFriend(mainForm);
            MSCMIDlet.mainForm.startTimer();
            MSCMIDlet.mainForm.show();
            return;
        }
        MSCMIDlet.instance.gaugeState = 1;
        //httpPoster.sendList(mainForm);
        /*if (strUserID.equals(oldOwner)) {
            if (PkgTools.getControl().equals("0")) {
                getMsgDlg.switchControl();
            }
            blackList.loadList();
        } else {
            PkgTools.setOtherInfo(strUserID, "1", blackList);
        } */
        //PkgTools.setUserInfo(strUserID, strPasswd);
    }

}
